﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using AvalonDock;
using System.Collections.Specialized;
using System.Windows.Controls;
using System.Windows;
using QinTools.ViewModel.Documents;

namespace QinTools.View
{
    public class DocumentRepository
    {
        #region Properties
        public static DocumentRepository Instance { get; private set; }
        public ObservableCollection<DocumentContent> Documents { get; private set; }
        public Document CurrentDocument { get; private set; }
        #endregion
        #region Constructors
        static DocumentRepository()
        {
            Instance = new DocumentRepository();
        }
        private DocumentRepository()
        {
            PepareDocumentList();
            DocumentTabSelectionChangedHandler = new SelectionChangedEventHandler(DocumentTab_SelectionChanged);
        }
        #endregion
        #region Public Interface
        public void CreateDocument<T>(T viewModel, string baseTitle)
        {
            var document = new DocumentContent();
            document.DataContext = viewModel;
            document.Title = GetNewTitle(baseTitle);
            Documents.Add(document);
        }

        public string GetNewTitle(string baseTitle)
        {
            int i = 1;
            string name = baseTitle + " " + i.ToString();

            while (Documents.Any(d => d.Title == name))
            {
                i++;
                name = baseTitle + " " + i.ToString();
            }
            return name;
        }
        #endregion
        #region Delegates
        public SelectionChangedEventHandler DocumentTabSelectionChangedHandler { get; private set; }
        #endregion
        #region Private Methods
        private void PepareDocumentList()
        {
            Documents = new ObservableCollection<DocumentContent>();
            Documents.CollectionChanged += new NotifyCollectionChangedEventHandler(Documents_CollectionChanged);
        }
        #endregion
        #region Event Handlers
        private void Documents_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            // TODO: handle documents being closed
        }

        private void DocumentTab_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MessageBox.Show("bam!");
        }
        #endregion
    }
}
